package com.sensePlusVR.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensePlusVR.activity.follow.FollowDetailActivity;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.ActorItem;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.CollectionFollowManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;

import java.util.List;

@SuppressLint("HandlerLeak")
@SuppressWarnings("unused")
public class FollowFollowAdapter extends
		RecyclerView.Adapter<FollowFollowAdapter.ViewHolders>{
	private static final String TAG = FollowFollowAdapter.class.getSimpleName();
	private List<ActorItem> followFollowList;
	private Context context;
	private DataCenter dataCenter;
	
	public static final String KEY = FollowFollowAdapter.class.getSimpleName();
	
	private MyHandler handler;
	
	EventListener listenerActors = new EventListener(){

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (Params == null || data == null)
				return;
			if (event != CollectionFollowManager.EventFollowCollectionGot){
				if ((event - CollectionFollowManager.EventErrorBase == CollectionFollowManager.EventFollowAdded)
					||(event - CollectionFollowManager.EventErrorBase == CollectionFollowManager.EventFollowDeled)
					||(event == CollectionFollowManager.EventFollowAdded)
					||(event == CollectionFollowManager.EventFollowDeled))
				updateFollowList(event, (Integer)data);
			}else if(event == CollectionFollowManager.EventFollowCollectionGot){}
		}
	};
	
	private int getIndex(List<ActorItem> list, int actorId){
		for (int i = 0; i < list.size(); i++){
			ActorItem item = list.get(i);
			if (item.getId() == actorId){
				return i;
			}
		}
		return -1;
	}
	
	private boolean listContainsOne(List<ActorItem> list, int actorId)
	{
		if (getIndex(list, actorId) < 0)
			return false;
		return true;
	}
	void updateFollowList(final int event, final Integer actorId){
		MyLog.d(TAG, "!EventFollowCollectionGot id : " + actorId);
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				MyLog.e(TAG, "follow event="+event);
				if (event == CollectionFollowManager.EventFollowAdded){
					ActorItem actorItem = dataCenter.getActorById(actorId);
					MyLog.d(TAG, "actorItem add : " + actorItem);
					if (!listContainsOne(followFollowList,actorItem.getId())) {
						followFollowList.add(0, actorItem);
						//notifyItemInserted(0);
						notifyDataSetChanged();
					}
				}else if (event == CollectionFollowManager.EventFollowDeled){
					ActorItem actorItem = dataCenter.getActorById(actorId);
					MyLog.d(TAG, "actorItem delete : " + actorItem);
					int pos = getIndex(followFollowList,actorItem.getId());
					if (pos >= 0) {
						followFollowList.remove(pos);
						//notifyItemRemoved(pos);
						notifyDataSetChanged();
					}
				}else if (event >= CollectionFollowManager.EventErrorBase) {
					int errEvent = event;
					errEvent -= CollectionFollowManager.EventErrorBase;
					if (errEvent == CollectionFollowManager.EventFollowAdded){
						for (ActorItem item: followFollowList){
							if (actorId == item.getId()){
								int pos = getIndex(followFollowList, item.getId());
								if (pos >= 0) {
									followFollowList.remove(pos);
									//notifyItemRemoved(pos);
									notifyDataSetChanged();
								}
								break;
							}
						}
						//updateFollowed(0);//add error, set follow to 0
					}else if (errEvent == CollectionFollowManager.EventFollowDeled){
						//updateFollowed(1);
						ActorItem actorItem = dataCenter.getActorById(actorId);
						if (!listContainsOne(followFollowList,actorItem.getId())) {
							followFollowList.add(actorItem);
							//notifyItemInserted(followFollowList.size()-1);
							notifyDataSetChanged();
						}
					}
				}
				//holder.detail_favour_tv.setText(String.valueOf(citem.getUp()));
			}
		});
	}
	
	public FollowFollowAdapter(Context context, List<ActorItem> followFollowList) {
		this.context = context;
		this.followFollowList = followFollowList;
		dataCenter = DataCenter.getInstans();
		
		handler = new MyHandler();
	}

	public class MyHandler extends Handler{
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg != null && msg.what == FollowDetailActivity.MSG_ACTIVITY_FULLY_DISPLAY && msg.obj.equals(KEY)){
				MyLog.d(TAG, "handle notify...");
				notifyDataSetChanged();
			}
		}
	}
	
	@Override
	public int getItemCount() {
		return followFollowList.size();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public ViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(
				R.layout.fragment_follow_follow_item, parent, false);
		MyLog.d(TAG, "onCreateViewHolder....");
		return new ViewHolders(view);
	}

	@Override
	public void onBindViewHolder(final ViewHolders holder, int position) {
		ActorItem actorItem = followFollowList.get(position);
		MyLog.d(TAG, "onBindViewHolder position : " + position);
		MyLog.d(TAG, "onBindViewHolder actorItem : " + actorItem.toString());
		holder.itemView.setTag(R.id.tag_follow_follow_obj, actorItem);
		holder.itemView.setTag(R.id.tag_follow_follow_position, position);
		int followCount = actorItem.getUserfollowcount() < 0?0:actorItem.getUserfollowcount();
		holder.follow_consequence.setText(actorItem.getName());
		holder.follow_count_tv.setText(String.valueOf(followCount));
		holder.setMyPosition(position);

		String imageUrl = actorItem.getImgurl();
		MyLog.d(TAG, "imageUrl :" + imageUrl);
		holder.follow_cover_default_iv.setVisibility(View.VISIBLE);
		holder.follow_cover_iv.setVisibility(View.INVISIBLE);
    	holder.follow_cover_default_iv.setImageResource(R.drawable.loadng_icon);
		ImageLibrary.getInstance().getImageBitmap(context, imageUrl,
				new Callback() {

					@Override
					public void onImageDownloaded(Bitmap bitmap) {
						MyLog.d(TAG, "bitmap : " + bitmap);
					if (bitmap != null){
						holder.follow_cover_default_iv.setVisibility(View.INVISIBLE);
						holder.follow_cover_iv.setVisibility(View.VISIBLE);
						holder.follow_cover_iv.setImageBitmap(bitmap);
					}
					}
				});
		
		
		String createTime = actorItem.getCreatetime();
		createTime = DateTimeUtil.removeZoneTime(createTime);
		if(DateTimeUtil.isLessPreviousMonth(createTime)){
			holder.follow_follow_new_iv.setVisibility(View.VISIBLE);
		}else{
			holder.follow_follow_new_iv.setVisibility(View.INVISIBLE);
		}
		
		List<GameItem> actorGameList = dataCenter.getGameListByActorName(actorItem.getName(), false,true);
		if(actorGameList != null && actorGameList.size() > 0){
			GameItem gameItemFirst = actorGameList.get(0);
			String createTimeInner = gameItemFirst.getCreatetime();
			createTimeInner = DateTimeUtil.removeZoneTime(createTimeInner);
			 
			 boolean isFisrtClick = MySharedPreferences.getBoolean(context, String.valueOf(actorItem.getId()));
			if(DateTimeUtil.isLessPreviousMonth(createTimeInner) && !isFisrtClick){
				holder.follow_follow_redcircle_iv.setVisibility(View.VISIBLE);
					VRApplication.handlers.put(KEY, handler);
			}else{
				holder.follow_follow_redcircle_iv.setVisibility(View.GONE);
			}
			
		}
		
		holder.follow_follow_fram.setOnClickListener(new MyOnClickListener(holder,position));
	}
	
	public void onResume(){
		dataCenter.addFCEventListener(listenerActors, this, KEY);
	}
	
	
	public void onPause(){
		dataCenter.addFCEventListener(null, this, KEY);
	}
	
	/**
	 * 批量更新数据
	 * 
	 * @param gameList
	 */
	public void refreshData() {
		notifyDataSetChanged();
	}
	
	/**
	 * 单个更新数据
	 * @param item
	 */
	public void add(ActorItem item) {
		followFollowList.add(item);
		MyLog.d(TAG, "followFollowList size : " + followFollowList.size());
		notifyItemInserted(followFollowList.size() - 1);
	}
	
	public void del(ActorItem item){
		
	}

	class ViewHolders extends RecyclerView.ViewHolder {
		public RelativeLayout follow_follow_relative;
		public FrameLayout follow_follow_fram;
		public ImageView follow_cover_default_iv;
		public ImageView follow_cover_iv;
		public ImageView follow_follow_new_iv;
		public ImageView follow_follow_redcircle_iv;
		public TextView follow_consequence;
		public TextView follow_count_tv;
		public int myPosition;
		
		public int getMyPosition() {
			return myPosition;
		}

		public void setMyPosition(int myPosition) {
			this.myPosition = myPosition;
		}

		public ViewHolders(View itemView) {
			super(itemView);
			follow_follow_relative = (RelativeLayout) itemView.findViewById(R.id.follow_follow_relative);
			follow_follow_fram = (FrameLayout) itemView.findViewById(R.id.follow_follow_fram);
			follow_cover_default_iv = (ImageView) itemView
					.findViewById(R.id.follow_cover_default_iv);
			follow_cover_iv = (ImageView) itemView
					.findViewById(R.id.follow_cover_iv);
			follow_follow_redcircle_iv = (ImageView) itemView
					.findViewById(R.id.follow_follow_redcircle_iv);
			follow_follow_new_iv = (ImageView) itemView
					.findViewById(R.id.follow_follow_new_iv);
			follow_consequence = (TextView) itemView
					.findViewById(R.id.follow_consequence);
			follow_count_tv = (TextView) itemView
					.findViewById(R.id.follow_count_tv);
			
			//动态设置View高度，避免某类手机对图片压缩问题，使得图片始终保持4：5
			LayoutParams lp = follow_follow_relative.getLayoutParams();
			int gapDP = (context.getResources().getDimensionPixelSize(R.dimen.padding_left_unify_follow_recycler)*2
					+ context.getResources().getDimensionPixelSize(R.dimen.padding_follow_follow)*2);
			MyLog.d(TAG, "gapDP : " + gapDP);
			lp.height = (int) ((DensityUtil.getScreenWidth(context) - gapDP) * 1.25);
			follow_follow_relative.setLayoutParams(lp);
			
		}
	}
	
	public class MyOnClickListener implements View.OnClickListener {
		private ViewHolders holder;
		private ActorItem item;
		private int position;
		
		public MyOnClickListener(ViewHolders holder,int position) {
			this.holder = holder;
			this.position = position;
			if(position<followFollowList.size()){
				this.item = followFollowList.get(position);
			}

		}

		
		
		@Override
		public void onClick(View v) {
			MyLog.d(TAG, "onClick position : " + position);
			switch (v.getId()) {
			case R.id.follow_follow_fram:
				MyPageJump.pageJumpAddObject(context, FollowDetailActivity.class, item, Constant.FROM_FOLLOW_FOLLOW);	
				break;
			}
		}
	}
}
